<template>
  <view class="post-section">
    <up-sticky :offset-top="126" @change="handleStickyChange">
      <view class="category-menu">
        <scroll-view scroll-x="true" class="category-scroll">
          <view
              class="category-item"
              :class="activeCategory === index ? 'active' : ''"
              v-for="(item, index) in categories"
              :key="index"
              @click="handleCategoryChange(index)"
          >
            {{ item }}
          </view>
        </scroll-view>
      </view>
    </up-sticky>

    <!-- 圈子动态 -->
    <view v-if="activeCategory === 0 || activeCategory === 1">
      <view class="post-list">
        <!-- 加载状态 -->
        <view v-if="loading" class="loading">
          <up-icon type="loading" size="40"></up-icon>
          <text>加载中...</text>
        </view>

        <!-- 空状态 -->
        <view v-else-if="circlePosts.length === 0" class="empty-state">
          <up-icon name="empty" size="60" color="#ccc"></up-icon>
          <text class="empty-text">暂无帖子数据</text>
        </view>

        <!-- 帖子列表 -->
        <view v-else>
          <view v-for="post in circlePosts" :key="post.id" class="post-card" @click="goToArticle(post.id)">
            <view class="post-header">
              <up-avatar
                  :src="post.user?.avatar || '/static/default-avatar.png'"
                  size="40"
                  @click="navigateToUserProfile(post.user?.userId)"
              ></up-avatar>
              <view class="user-info">
                <text class="username">{{ post.user?.nickname || '匿名用户' }}</text>
                <view class="user-tags">
                  <text class="campus">{{ post.user?.campus || '未知校区' }}</text>
                  <text class="grade">{{ post.user?.grade ? `${post.user.grade}级` : '未知年级' }}</text>
                </view>
              </view>
              <text class="post-time">{{ formatTime(post.createTime) }}</text>
              <text v-if="post.top" class="top-tag">置顶</text>
            </view>

            <view class="post-content">
              <text>{{ post.content }}</text>
              <!-- 图片展示（核心修复：处理flie字段） -->
              <view v-if="post.flie" class="image-container">
                <view
                    class="multi-images"
                    v-if="parseImageUrls(post.flie).length > 0"
                >
                  <up-image
                      v-for="(img, idx) in parseImageUrls(post.flie)"
                      :key="idx"
                      :src="img"
                      mode="aspectFill"
                      width="220rpx"
                      height="220rpx"
                      class="image-item"
                      @error="handleImageError"
                  ></up-image>
                </view>
              </view>
            </view>

            <view class="post-footer">
              <view class="action-item">
                <up-icon name="eye" size="22" color="#909399"></up-icon>
                <text>{{ post.viewCount || 0 }}</text>
              </view>
              <view class="action-item" @click.stop="handleLike(post.id, post.likeCount)">
                <up-icon name="heart" size="22" color="#909399"></up-icon>
                <text>{{ post.likeCount || 0 }}</text>
              </view>
              <view class="action-item">
                <up-icon name="chat" size="22" color="#909399"></up-icon>
                <text>{{ post.commentCount || 0 }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 闲置市场 -->
    <view v-if="activeCategory === 2">
      <view class="u-page">
        <view class="goods-list">
          <view
              class="goods-item"
              v-for="(item, index) in goodsList"
              :key="index"
              @click="goToGoodsDetail(item)"
              style="cursor: pointer;"
          >
            <view class="user-profile" @click.stop="navigateToGoodsUser(item.userId)">
              <image
                  :src="item.avatar || '/static/default-avatar.png'"
                  mode="widthFix"
                  class="user-avatar"
              ></image>
              <text class="user-nickname">{{ item.nickName || '匿名用户' }}</text>
            </view>

            <view class="goods-info">
              <up-text :text="item.title" margin="0 0 8px 0" bold></up-text>
              <up-text :text="item.description" margin="0 0 8px 0"></up-text>
              <up-album :urls="item.file ? JSON.parse(item.file) : []"></up-album>
              <view class="goods-footer">
                <up-text :text="'¥' + item.price" type="danger" bold size="16"></up-text>
                <up-text :text="item.status || '出售中'" type="success"></up-text>
              </view>
            </view>
          </view>

          <view v-if="goodsList.length === 0" class="empty-state">
            <up-icon name="goods" size="60" color="#ccc"></up-icon>
            <text class="empty-text">暂无商品数据</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getAllArticles } from '@/apis/homeAPI';
import { selectList } from '@/apis/shopAPI';
import { toggleLike } from '@/apis/articleApi';

// 用户信息获取（修复：使用同步方法）
const userInfo = uni.getStorageSync("userInfo") || {};
const userId = userInfo.userId || 0;

// 导航到用户 profile
const navigateToUserProfile = (userId) => {
  if (!userId) return;
  uni.navigateTo({ url: `/pages/profile/profile?userId=${userId}` });
};

// 导航到商品发布者主页
const navigateToGoodsUser = (userId) => {
  if (!userId) return;
  uni.navigateTo({ url: `/pages/home/userDetails?userId=${userId}` });
};

// 状态管理
const activeCategory = ref(0);
const categories = ref(['全部', '圈子动态', '闲置市场']);
const loading = ref(false);
const circlePosts = ref([]);
const goodsList = ref([]);

// Props定义
defineProps({
  marginTop: {
    type: String,
    default: '30rpx'
  }
});

// 切换分类
const handleCategoryChange = (index) => {
  activeCategory.value = index;
  if (index === 0 || index === 1) fetchAllArticles();
  if (index === 2) fetchGoodsList();
};

// 解析图片URL（处理flie字段的JSON数组）
const parseImageUrls = (flieStr) => {
  try {
    if (!flieStr) return [];
    const urls = JSON.parse(flieStr);
    // 过滤无效URL
    return Array.isArray(urls)
        ? urls.filter(url => typeof url === 'string' && url.trim() !== '')
        : [];
  } catch (error) {
    console.error('图片解析失败:', error, '原始数据:', flieStr);
    return [];
  }
};

// 图片加载错误处理
const handleImageError = (event) => {
  console.error('图片加载失败:', event.detail);
  // 可在这里替换为默认图
};

// 获取帖子数据（核心：处理flie字段）
const fetchAllArticles = async () => {
  loading.value = true;
  try {
    const response = await getAllArticles();
    if (response.data.code === 200) {
      const processedPosts = (response.data.data || []).map(post => ({
        ...post,
        user: post.user || {},
        // 修复：使用接口返回的flie字段（修正拼写错误）
        flie: post.flie || '',  // 保留原始字段用于图片解析
        viewCount: post.viewCount || 0,
        likeCount: post.likeCount || 0,
        commentCount: post.commentCount || 0
      }));
      circlePosts.value = processedPosts;
    } else {
      uni.showToast({ title: '获取数据失败', icon: 'none' });
    }
  } catch (error) {
    console.error('获取帖子失败:', error);
    uni.showToast({ title: '网络错误', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// 获取商品列表
const fetchGoodsList = async () => {
  loading.value = true;
  try {
    const response = await selectList({});
    if (response.data.code === 200) {
      const processedGoods = (response.data.data.list || []).map(goods => ({
        ...goods,
        avatar: goods.avatar || '/static/default-avatar.png',
        nickName: goods.nickName || '匿名用户',
        status: goods.status || '出售中'
      }));
      goodsList.value = processedGoods;
    } else {
      uni.showToast({ title: '获取商品数据失败', icon: 'none' });
    }
  } catch (error) {
    console.error('获取商品失败:', error);
    uni.showToast({ title: '网络错误', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// 跳转到文章详情
const goToArticle = (id) => {
  if (id) uni.navigateTo({ url: `/pages/article/article?id=${id}` });
};

// 跳转到商品详情
const goToGoodsDetail = (item) => {
  if (!item) return;
  uni.navigateTo({
    url: `/pages/shop/shop-detail?itemId=${item.id}`,
    success: (res) => {
      res.eventChannel.emit('acceptDataFromOpenerPage', { itemId: item.id, itemData: item });
    }
  });
};

// 时间格式化
const formatTime = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const now = new Date();
  const diffMs = now - date;
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));

  if (diffHours < 1) return `${Math.floor(diffMs / 60000)}分钟前`;
  if (diffHours < 24) return `${diffHours}小时前`;
  if (diffHours < 720) return `${Math.floor(diffHours / 24)}天前`;
  return `${date.getMonth() + 1}月${date.getDate()}日`;
};

// 吸顶状态变化
const handleStickyChange = (isFixed) => {
  console.log(isFixed ? '已吸顶' : '未吸顶');
};

// 点赞处理
const handleLike = async (targetId) => {
  if (!targetId || !userId) return;
  try {
    const response = await toggleLike({ userId, targetId, targetType: 1 });
    if (response.data.code === 200) {
      circlePosts.value = circlePosts.value.map(post =>
          post.id === targetId ? { ...post, likeCount: response.data.data } : post
      );
    } else {
      uni.showToast({ title: '点赞失败', icon: 'none' });
    }
  } catch (error) {
    console.error('点赞失败:', error);
    uni.showToast({ title: '网络错误', icon: 'none' });
  }
};

// 初始加载
onMounted(() => {
  fetchAllArticles();
});
</script>

<style lang="scss" scoped>
/* 分类菜单样式 */
.category-menu {
  margin-bottom: 16px;
  padding: 0 15rpx;
}

.category-scroll {
  white-space: nowrap;
  padding: 10rpx 0;
}

.category-item {
  display: inline-block;
  padding: 12rpx 24rpx;
  margin-right: 15rpx;
  background-color: #f8f8f8;
  border-radius: 30rpx;
  font-size: 28rpx;
  color: #333;
}

.category-item.active {
  background-color: #007aff;
  color: #fff;
}

/* 帖子列表样式 */
.post-section {
  width: 700rpx;
  margin: 0 auto;
}

.post-list {
  width: 670rpx;
  padding: 0 20rpx;
}

.post-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 25rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.post-header {
  width: 100%;
  min-height: 80rpx;
  display: flex;
  align-items: center;
  margin-bottom: 25rpx;
  position: relative;
}

.user-info {
  margin-left: 20rpx;
}

.username {
  font-size: 32rpx;
  font-weight: 500;
  color: #1c0101;
  display: block;
}

.user-tags {
  display: flex;
  margin-top: 8rpx;
}

.user-tags text {
  font-size: 24rpx;
  color: #666;
  margin-right: 15rpx;
}

.post-time {
  position: absolute;
  right: 0;
  top: 0;
  font-size: 24rpx;
  color: #999;
}

.top-tag {
  position: absolute;
  right: 0;
  bottom: 0;
  background: #f56c6c;
  color: #fff;
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
}

.post-content {
  font-size: 30rpx;
  color: #333;
  line-height: 1.6;
  margin-bottom: 25rpx;
}

/* 图片容器样式 */
.image-container {
  margin-top: 15rpx;
}

.multi-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.image-item {
  margin-bottom: 10rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.post-footer {
  display: flex;
  padding-top: 20rpx;
  border-top: 1rpx solid #ebeef5;
}

.action-item {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
  color: #909399;
  font-size: 26rpx;
}

.action-item text {
  margin-left: 8rpx;
}

/* 加载状态 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 50rpx 0;
}

.loading text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #666;
}

/* 闲置商品样式 */
.u-page {
  padding: 16px;
}

.goods-list {
  width: 100%;
  padding: 0 10rpx;
}

.goods-item {
  display: flex;
  margin-bottom: 25rpx;
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.user-profile {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 15rpx;
  width: 80rpx;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  object-fit: cover;
}

.user-nickname {
  margin-top: 8rpx;
  font-size: 24rpx;
  text-align: center;
  width: 80rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-info {
  flex: 1;
}

.goods-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15rpx;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-text {
  margin-top: 20rpx;
  font-size: 30rpx;
}
</style>